/**
 * 保留两位小数并且避免浮点数精度失真
 * @param {number} number 需要处理的数值
 * @param {number} decimals 保留的小数位数
 * @returns {string} 处理后的数值
 */
export function roundToDecimals(number, decimals) {
    const factor = Math.pow(10, decimals);
    // 使用 (number + Number.EPSILON) * factor 解决浮点数精度问题
    // return (Math.floor((number + Number.EPSILON) * factor) / factor).toFixed(decimals);
    return  (amendNumber(Math.floor(amendNumber(number, factor, "*")), factor, "/")).toFixed(decimals)
}

export function addroundToDecimals(num1, num2) {
    return amendNumber(num1, num2, "+")
}

/**
 * 小数精确度处理
 * @param {number} num1 数字
 * @param {number} num2 数字
 * @param {string} symbol +-*\/符号
 */
function amendNumber(num1, num2, symbol) {
    let result
    let str1Length = 0
    let str2Length = 0

    // 解决整数没有小数点方法
    try {
        str1Length = (num1 + '').split('.')[1].length
    } catch (e) {
        //
    }
    try {
        str2Length = (num2 + '').split('.')[1].length
    } catch (error) {
        //
    }
    const step = Math.pow(10, Math.max(str1Length, str2Length))
    const n1 = Number((num1 * step).toFixed()) // 转换成整数 0.0012 * 100000000 = 119999.99999999999
    const n2 = Number((num2 * step).toFixed()) // 转换成整数 0.0012 * 100000000 = 119999.99999999999
    switch (symbol) {
        case '+':
            result = (n1 + n2) / step
            break
        case '-':
            result = (n1 - n2) / step
            break
        case '*':
            result = (n1 * n2) / (step * step)
            break
        case '/':
            result = n1 / n2
            break
        default:
            break
    }
    return result
}


